<template>
  <div>
    <header-bar />
    <banner :slide="banner" />
    <tab-bar 
      :tab-list="nav"
      @change="tabChange"
    />
    <product-list
      :list="products"
    />
  </div>
</template>

<script>
import HeaderBar from './component/HeaderBar'
import Banner from './component/Banner'
import scroll from '@/mixins/scroll'

export default {
  name: 'HomePage',
  data () {
    return {
      banner: [],
      menu: [],
      nav: [],
      products: [],
      loadFlg: false,
      fetchParams: {
        page: 0,
        page_size: 5,
        brandId: 1
      }
    }
  },
  props: {},
  components: {
    HeaderBar,
    Banner
  },
  mixins: [scroll],
  created () {
    this.initData()
  },
  
  watch: {
    fetchParams: {
      handler: function () {
        this.getProductList()
      },
      deep: true, // 深度监听，可以监听到对象中任意属性的改变
      immediate: true // 立即执行，默认情况下watch只会在改变后执行，默认第一次不会触发，设置immediate为true，默认第一次就会触发了
    }
  },
  methods: {
    initData () {
      const servers = [
        this.$api.home.banner(),
        this.$api.home.menu(),
        this.$api.home.nav()
      ]
      Promise.all(servers).then(([banner, menu, nav]) => {
        console.log(banner)
        this.banner = banner.data
        this.menu = menu.data
        this.nav = nav.data
      })
    },

    async getProductList () {
      const list = await this.$api.product.list(this.fetchParams)
      if (this.fetchParams.page === 0) {
        this.products = list.data
      } else {
        this.products = this.products.concat(list.data)
      }
      this.loadFlg = false
    },

    tabChange (item) {
      this.fetchParams.brandId = item.id
      this.fetchParams.page = 0
    },

    onScrollBottom () {
      if (this.loadFlg) return
      this.loadFlg = true
      this.fetchParams.page += 1
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
